package development;

import java.util.Vector;

import state.GameImage;
import state.util.Hashtable;

public class AvatarCache {
  private static final int MAX_AVATAR_USE = 10;

  private static Hashtable avatarTable = new Hashtable();
  private static Hashtable lastTimeUseAvatar = new Hashtable();

  private static int numberOfAvatar;

  public static void putAvatar(String avatarId, GameImage image) {
    if (numberOfAvatar >= MAX_AVATAR_USE) {
      // Tìm và remove avatar lâu chưa xử dụng nhất
      Object oldestKey = "";
      int oldestTime = Integer.MAX_VALUE;
      Vector keys = avatarTable.keys();
      for (int i = 0; i < keys.size(); i++) {
        Object key = keys.elementAt(i);
        int lastTime = ((Integer) lastTimeUseAvatar.get(key)).intValue();
        if (lastTime < oldestTime) {
          oldestTime = lastTime;
          oldestKey = key;
        }
      }
      removeAvatar(oldestKey);
    }
    image.setStatic(true);
    avatarTable.put(avatarId, image);
    lastTimeUseAvatar.put(avatarId, new Integer((int) System.currentTimeMillis()));
  }
  
  public static void removeAvatar(Object avatarId) {
    GameImage image = (GameImage) avatarTable.get(avatarId);
    if (image != null) {
      image.setStatic(false);
      avatarTable.remove(avatarId);
      lastTimeUseAvatar.remove(avatarId);
    }
  }

  public static GameImage getAvatar(String avatarId) {
    if (avatarId == null) {
      return null;
    }
    
    GameImage image = (GameImage) avatarTable.get(avatarId);
    if (image != null) {
      lastTimeUseAvatar.put(avatarId, new Integer((int) System.currentTimeMillis()));
    }
    return image;
  }

  public static void clearAvatarCache() {
    Vector keys = avatarTable.keys();
    for (int i = 0; i < keys.size(); i++) {
      removeAvatar(keys.elementAt(i));
    }
    numberOfAvatar = 0;
    System.gc();
  }
}
